import net from "net";
import { mem, networkInterfaces, networkStats } from "systeminformation";

/**
 * 检查端口是否被占用
 * @param {number} port 端口号
 * @param {string} host 主机地址，默认为本地
 * @returns {Promise<boolean>} 如果端口被占用，则返回 true，否则返回 false
 */
export function checkPortOccupied(port, host = "127.0.0.1") {
  return new Promise((resolve, reject) => {
    const server = net.createServer();

    // 尝试监听该端口
    server.once("error", (err) => {
      if (err.name === "EADDRINUSE") {
        resolve(true); // 端口被占用
      } else {
        reject(err); // 其他错误
      }
    });

    // 如果端口空闲，则可以成功监听
    server.once("listening", () => {
      server.close(); // 关闭服务器，释放端口
      resolve(false); // 端口未占用
    });

    server.listen(port, host);
  });
}

// 获取网速
export async function createNetworkSpeedMonitor(): Promise<any> {
  let previousStats = {};

  async function getNetworkSpeed() {
    try {
      const currentStats = await networkStats();
      let totalDownloadSpeed = 0; // 总下载速度
      let totalUploadSpeed = 0; // 总上传速度

      currentStats.forEach((iface) => {
        if (previousStats[iface.iface]) {
          const downloadedBytes =
            iface.rx_bytes - previousStats[iface.iface].rx_bytes; // 下载字节数
          const uploadedBytes =
            iface.tx_bytes - previousStats[iface.iface].tx_bytes; // 上传字节数

          const downloadSpeed = Number(
            (((downloadedBytes / 1000) * 1000) / 1024).toFixed(2),
          ); // 下载速度，单位 KB/s
          const uploadSpeed = Number(
            (((uploadedBytes / 1000) * 1000) / 1024).toFixed(2),
          ); // 上传速度，单位 KB/s

          totalDownloadSpeed += downloadSpeed; // 累加总下载速度
          totalUploadSpeed += uploadSpeed; // 累加总上传速度
        }
      });

      // 更新 previousStats
      previousStats = currentStats.reduce((acc, iface) => {
        acc[iface.iface] = iface;
        return acc;
      }, {});

      return {
        download: totalDownloadSpeed,
        upload: totalUploadSpeed,
      };
    } catch (error) {
      console.error("Error fetching network stats:", error);
      return { download: 0, upload: 0 }; // 如果出错，返回默认值
    }
  }

  return getNetworkSpeed;
}

// 获取内存占用率
export async function getMemoryInfo() {
  try {
    const memory = await mem();
    const totalMemory = (memory.total / (1024 * 1024 * 1024)).toFixed(2); // 转换为GB
    const usedMemory = (memory.used / (1024 * 1024 * 1024)).toFixed(2); // 转换为GB
    const freeMemory = (memory.free / (1024 * 1024 * 1024)).toFixed(2); // 转换为GB
    const usedPercentage = (
      (Number(usedMemory) / Number(totalMemory)) *
      100
    ).toFixed(2);

    return { totalMemory, usedMemory, freeMemory, usedPercentage };
  } catch (error) {
    return { totalMemory: 0, usedMemory: 0, freeMemory: 0, usedPercentage: 0 };
  }
}
